package com.jiabowen.store.service.impl;

import com.jiabowen.store.entity.User;
import com.jiabowen.store.mapper.UserMapper;
import com.jiabowen.store.service.IUserService;
import com.jiabowen.store.service.exception.PasswordNotMatchExecption;
import com.jiabowen.store.service.exception.UpdateException;
import com.jiabowen.store.service.exception.UserNotFoundException;
import com.jiabowen.store.service.exception.UsernameDuplicatedException;
import jdk.jfr.events.ThrowablesEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.UUID;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void reg(User user) {
        // 通过user参数来获取传递过来的username
        String username = user.getUsername();
        //调用findByUsername(username)判断用户是否被注册过
        User result = userMapper.findByUsername(username);
        //判断结果集是否为空，如果不为空则抛出异常
        if (result != null){
            throw new UsernameDuplicatedException("用户名被占用");
        }

        /**
         * 密码加密处理:
         */
        String oldPassword = user.getPassword();
        //获取盐值（随即生成一个盐值）
        String salt = UUID.randomUUID().toString().toUpperCase();
        //将密码和盐值整体加密处理
        String password = getMD5Password(user.getPassword(), salt);
        //将加密后的密码补全到user对象中
        user.setPassword(password);
        //补全盐值
        user.setSalt(salt);


        //补全数据：isDelete设置为0
        user.setIsDelete(0);
        //补全数据：四个日志信息
        user.setCreatedUser(username);
        user.setModifiedUser(username);
        Date date = new Date();
        user.setCreatedTime(date);
        user.setModifiedTime(date);

        //执行注册业务功能的实现（row == 1）
        Integer rows = userMapper.insert(user);
        if (rows != 1){
            throw new UsernameDuplicatedException("用户在注册过程中产生了未知异常");
        }
    }

    @Override
    public User login(String username, String password) {
        //根据用户名来查询数据是否存在，如果不在则抛出异常
        User result = userMapper.findByUsername(username);
        if (result == null){
            throw new UserNotFoundException("用户数据不存在");
        }

        //检测用户的密码是否匹配
        //1.先获取到数据库中加密后的密码
        String oldPassword = result.getPassword();
        //2.和用户传递过来的密码进行比较
        //2.1先获取盐值，上一次在注册时自动生成的盐值
        String salt = result.getSalt();
        //2.2将用户的密码按照相同的md5算法规则进行加密
        String newMd5Password = getMD5Password(password, salt);
        if (!oldPassword.equals(newMd5Password)){
            throw new PasswordNotMatchExecption("密码错误");
        }

        //判断is_delete字段的值是否为1，1表示标记为删除
        if (result.getIsDelete() == 1){
            throw new UserNotFoundException("用户数据不存在");
        }

        User user = new User();
        user.setUid(result.getUid());
        user.setUsername(result.getUsername());
        user.setAvatar(result.getAvatar());
        return user;
    }

    /**
     *用户修改密码方法
     * @param uid 用户uid
     * @param username 用户名
     * @param oldPassword 当前用户旧密码
     * @param newPassword 当前用户新密码
     */
    @Override
    public void changePassword(Integer uid, String username, String oldPassword, String newPassword) {
        User result = userMapper.findUserById(uid);
        if (result == null || result.getIsDelete() == 1){
            throw new UserNotFoundException("用户数据不存在");
        }
        //原始密码和数据库中密码进行比较
        String salt = result.getSalt();
        String oldMd5Password = getMD5Password(oldPassword, salt);
        if (!oldMd5Password.equals(result.getPassword())){
            throw new PasswordNotMatchExecption("新密码与原来密码不同");
        }

        String newMd5Password = getMD5Password(newPassword, salt);
        //将新密码设置到数据库中，将新密码进行加密后再去更新
        Integer rows = userMapper.updatePasswordById(uid, newMd5Password, username, new Date());
        if (rows != 1){
            throw new UpdateException("更新数据时发生未知异常");
        }
    }

    @Override
    public User getUserById(Integer uid) {
        User result = userMapper.findUserById(uid);
        if (result.getIsDelete() == 1 || result == null){
            throw new UserNotFoundException("用户数据不存在");
        }
        User user = new User();
        user.setUsername(result.getUsername());
        user.setPhone(result.getPhone());
        user.setEmail(result.getEmail());
        user.setGender(result.getGender());
        return user;
    }

    /**
     *
     * @param uid 用户id 在session中
     * @param username 用户名称 在session中
     * @param user 用户对象的数据
     */
    @Override
    public void changeInfo(Integer uid, String username, User user) {
        User result = userMapper.findUserById(uid);
        if (result.getIsDelete() == 1 || result == null){
            throw new UserNotFoundException("用户数据不存在");
        }
        user.setUid(result.getUid());
//        user.setUsername(result.getUsername());
        user.setModifiedTime(new Date());
        user.setModifiedUser(username);

        Integer row = userMapper.updateInfoByUid(user);
        if (row != 1){
            throw new UpdateException("更新数据时发生未知异常");
        }
    }

    @Override
    public void changeAvatar(Integer uid, String avatat, String username) {
        //查询当前用户是否存在
        User result = userMapper.findUserById(uid);
        if (result == null){
            throw new UserNotFoundException("用户数据不存在");
        }
        Integer rows = userMapper.updateAvatarById(uid, avatat, username, new Date());
        if (rows != 1){
            throw new UpdateException("更新头像时产生未知异常");
        }
    }

    private String getMD5Password(String password,String salt){
        for (int i = 0; i < 3; i++) {
            password = DigestUtils.md5DigestAsHex((salt + password + salt).getBytes()).toUpperCase();
        }
        return password;
    }
}
